package com.cloud.gateway.filter;

import com.cloud.gateway.support.WebSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 上下文拦截器
 */
@Slf4j
@Component
public class WebContextFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        WebSupport.allowCors(response);

        ServerHttpRequest request = exchange.getRequest();
        if (CorsUtils.isCorsRequest(request)
                && (request.getMethod() == HttpMethod.OPTIONS || isWebSocketFirstRequest(request))) {
            return Mono.empty();
        }
        return chain.filter(exchange);
    }

    private boolean isWebSocketFirstRequest(ServerHttpRequest request) {
        if (request.getURI().getPath().endsWith("/info") && request.getQueryParams().getFirst("t") != null) {
            return true;
        }
        return false;
    }
}
